﻿namespace Chat_WebApi.Controllers.v1
{
    using System;
    using System.Collections.Generic;
    using System.IdentityModel.Tokens.Jwt;
    using System.Security.Claims;
    using System.Text;
    using System.Threading.Tasks;
    using AutoMapper;
    using Chat_Filter;
    using Chat_IService;
    using Chat_Model;
    using Chat_Model.ViewModel;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.Logging;
    using Microsoft.IdentityModel.Tokens;
    using Newtonsoft.Json;

    /// <summary>
    /// 授权
    /// </summary>
    [Route("/api/v1/[controller]")]
    [ApiController]
    public class AuthController : Controller
    {
        private readonly ILarUsersService _larUsers;
        private readonly IMapper _mapper;
        private readonly ILogger<AuthController> _logger;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="larUsers"></param>
        /// <param name="mapper"></param>
        /// <param name="logger"></param>
        public AuthController(
            ILarUsersService larUsers,
            IMapper mapper,
            ILogger<AuthController> logger)
        {
            this._larUsers = larUsers;
            this._mapper = mapper;
            this._logger = logger;
        }

        /// <summary>
        /// 登录接口.
        /// </summary>
        /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
        [HttpPost("login")]
        [OneFilter]
        public async Task<MessageModel<object>> Login([FromBody] LoginParam param)
        {
            LarUsers model =
                await this._larUsers.GetSingleAsync(x => x.Mobile == param.Mobile && x.Password == param.Password);
           if (model != null)
            {
                this._logger.LogInformation("LogInformation");
                this._logger.LogWarning("LogWarning");
                this._logger.LogDebug("LogDebug");
                this._logger.LogError("LogError");


                var modelDTo = this._mapper.Map<LarUsersDto>(model);

                var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("{069BD1DF-72D8-474B-8950-2C3EB03B2D03}"));
                var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
                var token = new JwtSecurityToken(
                    "Issuer",
                    "Audience",
                    new List<Claim>
                    {
                        new Claim(ClaimTypes.Role, "admin"),
                        new Claim(ClaimTypes.Gender, "Male"),
                        new Claim(ClaimTypes.UserData, JsonConvert.SerializeObject(model)),
                    },
                    expires: DateTime.UtcNow.AddMinutes(30),
                    signingCredentials: credentials);

                return new MessageModel<object>()
                {
                    Code = 200,
                    Message = "登录成功...",
                    Data = new
                    {
                        authorize = new
                        {
                            access_token = new JwtSecurityTokenHandler().WriteToken(token),

                            // access_token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJqdGkiOiJkZWZhdWx0XzVmYWU4MmNhOGJlZGM5LjMyNDQ5ODM2IiwiaWF0IjoxNjA1MjcyMjY2LCJuYmYiOjE2MDUyNzIyNjYsImV4cCI6MTYwNTI3OTQ2NiwidXNlcl9pZCI6MjA1NCwicGxhdGZvcm0iOiJ3aW5kb3dzIiwiand0X3NjZW5lIjoiZGVmYXVsdCJ9.XbB571f57pufM546Ue8mnt4YhL8igM9M3pATfOEieX4",
                            expires_in = 7200,
                        },
                        user_info = modelDTo,
                    },
                };
            }
             else
            {
                return new MessageModel<object>()
                {
                    Code = 305,
                    Message = "登录失败...",
                };
            }
        }

        /// <summary>
        /// 注册接口
        /// </summary>
        /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
        [HttpPost("register")]
        public async Task<MessageModel<List<object>>> Register([FromBody] RegisterParam param)
        {
            if (string.IsNullOrWhiteSpace(param.Sms_code))
            {
                return new MessageModel<List<object>>()
                {
                    Code = 305,
                    Message = "短信验证码不能为空..",
                    Data = new List<object>() { },
                };
            }

            LarUsers users = new LarUsers()
            {
                Nickname = param.Nickname,
                Mobile = param.Mobile,
                Password = param.Password,
            };
            if (await this._larUsers.InsertAsync(users))
            {
                return new MessageModel<List<object>>()
                {
                    Code = 200,
                    Message = "账号注册成功...",
                    Data = new List<object>() { },
                };
            }
            else
            {
                return new MessageModel<List<object>>()
                {
                    Code = 305,
                    Message = "账号注册失败...",
                    Data = new List<object>() { },
                };
            }
        }
    }
}